from datetime import datetime

from odoo import fields, models, api
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT


class MrpTaskInsertOrder(models.Model):
    _name = 's.mrp.task.insert.order.wizard'
    _description = 'Insert Order'

    product_id = fields.Many2one('product.product')
    line_ids = fields.One2many('s.mrp.task.insert.order.line.wizard', 'order_id')

    @api.onchange('product_id')
    def onchange_product_id(self):
        if not self.product_id:
            return
        production_ids = self.env['mrp.production'].search([
            ('product_id', '=', self.product_id.id),
            ('state', 'in', ('confirmed', 'progress'))
        ])
        line_vals_list = []
        for production in production_ids:
            line_vals_list.append((0, 0, {
                'production_id': production.id,
                'qty': production.product_uom_qty,
                'qty_pnl': production.panel_uom_qty
            }))
        self.line_ids = line_vals_list

    def action_confirm(self):
        date_str = self._context.get('date_str')
        if date_str:
            now = fields.Date.today()
            date_str = f'{now.year}-{date_str}'
            date = datetime.strptime(date_str, DEFAULT_SERVER_DATE_FORMAT)
        else:
            date = None
        for line in self.line_ids.filtered(lambda x: x.check):
            self.env['s.mrp.task'].production_scheduling(line.production_id, 1, date)


class MrpTaskInsertOrderLine(models.Model):
    _name = 's.mrp.task.insert.order.line.wizard'
    _description = 'Insert Order Line'

    order_id = fields.Many2one('s.mrp.task.insert.order.wizard')
    production_id = fields.Many2one('mrp.production', string='Production')
    delivery_date = fields.Datetime('Delivery Date', related='production_id.s_origin_delivery_date')
    check = fields.Boolean('Select')
    qty = fields.Integer('Qty')
    qty_pnl = fields.Integer('Qty(PNL)')
